<template>
  <div class="saas-upload">
    <div style="width: 100%; height: 100%">
      <input ref="fileInput" type="file" @change="handleChange" :multiple="multiple" v-show="false">
      <div @click="uploadBtn" v-loading="uploadLoading" style="width: 100%; height: 100%;">
        <slot ></slot>
      </div>
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from 'vue'
import { ElMessage } from 'element-plus'
import { formatDate } from "@/utils/d_times"
import {v4 as uuidv4} from 'uuid'
import OSS from 'ali-oss'
import * as imageConversion from 'image-conversion';
const client  = new OSS({
  region: 'oss-cn-hangzhou',
  accessKeyId: 'LTAI5t9joGPUQu8JxqitLjM7',
  accessKeySecret: 'mptSOB6CVQuDXA5Sq4Ad8fXQ4E7EFb',
  bucket: 'inwuoo-chats',
});
const props = defineProps({
  multiple: {
    type: Boolean,
    default: true
  },
  uploadType: {
    type: String,
    default: "img"
  },
  imgSize: {
    type: Number,
    default: 2200
  },
  imgWidth: {
    type: Number,
    default: 2000
  },
  videoSize:{
    type: Number,
    default: 51200
  }
})
const uploadLoading = ref(false)
const fileInput = ref()
const handleChange = async (event) => {
  uploadLoading.value = true
  const files = event.target.files
  for (let i = 0; i < files.length; i++) {
    let file = files[i]
    let fileSize = file.size
    let fileName = file.name
    if(props.uploadType === 'img' && isImage(fileName)) {
      let res = await zipImg(file)
      await putObject(res)
    }else if(props.uploadType === "video" && isVideo(fileName)){
      if(fileSize > 51200 * 1024){
        ElMessage.warning("视频文件不能大于50mb")
        return
      }
      await putObject(file)
    }else {
      if(props.uploadType === "img"){
        ElMessage.warning("请上传图片资源,请重新上传")
      }else if(props.uploadType === "video") {
        ElMessage.warning("请上传视频文件,请重新上传")
      }
    }
  }

  uploadLoading.value = false
  // 输出为 null
  clearFileInput()
}

const emits = defineEmits(["successUpload"])
const putObject = async (data) => {
  let type = getType(data.name);
  let time = formatDate(new Date(), 'yyyy/MM/dd')
  let newName = `chat_agent/image/${time}/${uuidv4()}_`
  let name =  newName + new Date().getTime() + Math.floor(Math.random() * 150) +`-10000000` + type;
  let result = await client.put(name, data)
  let imgUrl = result.url
  emits("successUpload", imgUrl)
}
const zipImg = async (file) => {
  return new Promise((resolve) => {
    imageConversion.compressAccurately(file, {
      width: props.imgWidth,
      size: props.imgSize
    }).then((res) => {
      resolve(res)
    })
  })
}
const uploadBtn = () => {
  fileInput.value.click()
}
const clearFileInput = () => {
  if(fileInput.value) {
    fileInput.value.value = ""
  }
}
const isImage = (str) => {
  str = str.toLowerCase()
  let reg = /\.(jpg|jpeg|webp|gif|png)$/
  return reg.test(str)
}
const isVideo = (str) => {
  str = str.toLowerCase()
  let reg = /\.(mp4)$/
  return reg.test(str)
}
const getType = (name) => {
  let index = name.lastIndexOf(".")
  let type = name.substring(index, name.length)
  return type.toLocaleLowerCase()
}
</script>

<style scoped lang="less">

</style>